import logging

from fastapi import APIRouter, Query

from app.controllers.menu import menu_controller
from app.schemas.base import Fail, Success
from app.schemas.menus import *

logger = logging.getLogger(__name__)

router = APIRouter()


@router.get("/list", summary="查看菜单列表")
async def tree_list(
    code: str = Query("", description="菜单编码"),
    name: str = Query("", description="菜单名称"),
):
    """
    查看菜单列表
    """
    rst = await menu_controller.tree_list(code, name)
    return Success(data=rst)


@router.get("/{menu_id}", summary="查看菜单")
async def get_by_id(menu_id: int):
    """
    根据id查询菜单
    :param menu_id: ID
    :return: 菜单信息
    """
    result = await menu_controller.get(id=menu_id)
    return Success(data=await result.to_dict())


@router.post("/", summary="创建菜单")
async def create(menu_in: MenuCreate):
    """
    创建菜单
    :param menu_in: 菜单对象
    :return: 操作结果
    """
    await menu_controller.create(obj_in=menu_in)
    return Success(msg="Created Success")


@router.put("/", summary="修改菜单")
async def update(menu_in: MenuUpdate):
    """
    修改菜单
    :param menu_in: 菜单对象
    :return: 操作结果
    """
    await menu_controller.update(id=menu_in.id, obj_in=menu_in)
    return Success(msg="Updated Success")


@router.delete("/{menu_id}", summary="删除菜单")
async def delete(menu_id: int):
    """
    删除菜单
    :param menu_id: ID
    :return: 操作结果
    """
    child_menu_count = await menu_controller.model.filter(parent_id=menu_id).count()
    if child_menu_count > 0:
        return Fail(msg="Cannot delete a menu with child menus")
    await menu_controller.remove(id=menu_id)
    return Success(msg="Deleted Success")
